<template>
  <view class="taskStep">
    <view class="header">
      <!-- #ifdef MP-WEIXIN -->
      <view :class="[showNav ? 'aa' : '']" style="z-index: 300">
        <uni-nav-bar left-icon="back" :title="title || '--'" statusBar="true" :fixed="false"
          backgroundColor="rgba(0, 0, 0, 0)" @clickLeft="handleBack"></uni-nav-bar>
      </view>
      <!-- #endif -->

      <!-- 头部部分header -->
      <view v-if="repairState !== 1" class="header_item">

        <view class="header_top" @click="toInfos(1)">
          <view class="header_top_left">
            <view class="name">
              {{
                cutLenght(
                  elevatorDetail.buildingName + elevatorDetail.elevatorAddress
                )
              }}
            </view>
            <view class="flex" style="width: 60rpx">
              <text></text>
            </view>
          </view>
          <view class="right" @click.stop="showPath">
            <image src="@/static/images/locations.png" class="close" style="width: 32rpx; height: 32rpx"></image>
            导航
          </view>
        </view>
        <view class="header_bottom">
          {{ elevatorDetail.buildingAddress }}
        </view>
        <view class="header_bottom info" style="margin-top: 8rpx" @click.stop="toInfos">
          <view class="header_bottom_left">
            <view>
              {{ elevatorDetail.brandName || "--" }}
            </view>

            <view class="str"> | </view>
            <view>
              {{ elevatorDetail.privateNum || "--" }}
            </view>
          </view>
          <view class="header_bottom_right">
            <view v-if="!elevatorDetail.isFull" style="display: flex; align-items: center">
              <image src="@/static/images/tips.png" class="close" style="width: 32rpx; height: 32rpx">
              </image>
              <uni-icons color="#999" size="18" type="arrowright" />
            </view>
          </view>
        </view>
      </view>
      <view v-if="repairState === 1" class="header_item">
        <view class="header_top" @click="showPath">
          <view class="header_top_left">{{
            cutLenght(
              elevatorDetail.buildingName + elevatorDetail.elevatorAddress
            )
          }}</view>
          <view class="flex" style="width: 94rpx">
            <image src="/static/images/maintain/location.png" class="close" style="width: 32rpx; height: 32rpx">
            </image>
            导航
          </view>
        </view>
        <view class="header_bottom">
          {{ elevatorDetail.buildingAddress }}
        </view>
        <view class="header_bottom" @click="toInfos" style="
            display: flex;
            justify-content: space-between;
            padding: 20rpx 0;
          ">
          <view>
            <text>{{ elevatorDetail.brandName || "-" }}</text>
            <text style="padding: 0 10rpx">|</text>
            <text> {{ elevatorDetail.privateNum || "-" }}</text>
          </view>
          <view style="display: flex; align-items: center">
            <image src="/static/images/tips.png" class="close" style="width: 32rpx; height: 32rpx"></image>
            <uni-icons color="#999" size="18" type="arrowright" />
          </view>
        </view>
      </view>
      <image
        src="https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20221012/c1a6e9996af7e11408d283b788eb2b33.png"
        mode="" class="bg"></image>
    </view>
    <!-- <view class="content" :style="{margin:repairState === 1 ?'-70rpx auto;':'-100rpx auto;'}"> -->
    <!-- <text v-for="(item, index) in templateList" :key="index">{{ index == 0 ? "" : "、" }}{{ item }}</text> -->
    <view class="content" :style="{ top: navHeight().top + 150 + 'px;' }">
      <view class="content_chi">
        <view class="t_name">
          任务跟踪
        </view>
        <view class="t_Times" v-if="planTimes">
          <image src="/static/images/maintain/funnel.png" mode=""></image>
          <text>工单实际作业时长：{{ planTimes + "分钟" }}</text>
          <text v-if="strText">{{ strText }}</text>
        </view>
        <view class="stepInfoBox"> 
          <stepInfo :partsShow="partsShow" :dataList="dataArray" @seeClick="seeClick"
            @seeClickDetial="seeClickDetial" />
        </view>
        <view v-if="dataArray.length <= 0" style="
            height: 200rpx;
            line-height: 200rpx;
            color: #cccccc;
            text-align: center;
          ">
          暂无数据进度
        </view>
      </view>
    </view>

    <!-- 查看详情证明 -->
    <uni-popup ref="logPopup" :mask-click="true" type="bottom">
      <view class="calendarEdit">
        <view class="edit_bor" @click="$refs.logPopup.close()">
          <view class="down-btn"></view>
        </view>
        <view class="edit_content">
          <view class="content_tit">分配计划详情</view>
          <view class="content_uper">
            <view class="">
              <image src="@/static/images/repairFitting/signMonthR.png" mode=""></image>
              <text>初始计划日期:</text>
            </view>
            <view class="">{{ mPlanDate }}</view>
          </view>
          <view class="content_down">
            <view class="">
              <image src="@/static/images/group.png" mode=""></image>
              <text>计划执行人:</text>
            </view>
            <view class="">
              <user-list :taskStep="true" :list="userListArr"></user-list>
            </view>
          </view>
        </view>
        <view class="BA_item_botm">
          <view class="botm" @click="$refs.logPopup.close()">我知道了</view>
        </view>
      </view>
    </uni-popup>
    <previewMedia ref="previewMedia"></previewMedia>
  </view>
</template>

<script>
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
import stepInfo from './stepInfoplus.vue';
import { getSelectWorkTracks, lastMaintenance } from '@/apis/taskStepPage.js';
import { navHeight } from '@/utils/tools.js';
import { getDays } from '@/utils/utils.js';
import userlist from '@/components/user-list/user-list.vue';
import { getPlanDetail, getPlandUser } from '@/apis/workOrder.js';
import { getPathInfo } from '@/utils/watermarkTool.js';
export default {
	data() {
		return {
			dataArray: [],
			dataArrayParts: [
				{ name: '提交配件申请', desc: '', status: 0 },
				{ name: '提交配件申请', desc: '', status: 1 },
				{ name: '配件审核', desc: '', status: 2 },
				{ name: '待回签', desc: '', status: 10 },
				{ name: '待采购', desc: '', status: 11 },
				{ name: '配件报价', desc: '', status: 3 },
				{ name: '待收货', desc: '', status: 12 },
				{ name: '配件发货', desc: '', status: 4 },
				{ name: '分配任务', desc: '', status: 5 },
				{ name: '更换中', desc: '', status: 6 },
				{ name: '已完成', desc: '', status: 7 },
			],
			showImg: false, // 查看图片状态
			elevatorDetail: {
				buildingName:'',
				buildingAddress:'',
				elevatorAddress:''
			},
			taskTitle: '',
			title: '保养任务追踪',
			templateList: [],
			typeList: ['', '半月', '季度', '半年', '年度', '自定义'],
			repairState: 0, // 维修页面状态
			navHeight: navHeight,
			planTimes: null,
			strText: '',
			showNav: false,
			getDaysStr: '',
			mPlanDate: '',
			userListArr: [],
			partsShow: true,
		};
	},
	components: {
		uniNavBar,
		stepInfo,
		userlist,
	},
	props: {

	},
	computed: {},
	// 监听页面滚动
	onPageScroll(e) {
		// console.log('e.scrollTop',e.scrollTop)
		if (e.scrollTop > 100) {
			this.showNav = true;
			this.scrollTop = e.scrollTop;
		} else {
			this.showNav = false;
		}
	},
	mounted() { },
	onLoad(opt) {
		if (Object.keys(opt).length <= 0) {
			return;
		}
		// opt.partsID = '1546811441862455297'

		this.templateList = JSON.parse(opt.list || '[]');
		this.elevatorDetail = JSON.parse(opt.obj || '{}');
		this.repairState = Number(opt.state) || 0;
		let planCheckType = this.elevatorDetail.planCheckType;

		if (opt.partsID) {
			this.title = '配件更换详情';
			this.partsShow = true;
			this.initPartsStep(opt.partsID);
			return;
		}
		this.partsShow = false;
		this.initGetStep(this.elevatorDetail.planId);
	},
	methods: {
		// 获取上次保养时间
		getLastMaintenance(id) {
			return new Promise((resolve) => {
				lastMaintenance({ planId: id }).then((res) => {
					// console.log(res,'时间',res.data.lastPlanDate,res.data.planDate.slice(0,10));
					const { lastPlanDate, planDate } = res.data;
					// console.log(getDays(res.data.lastPlanDate,res.data.planDate))
					let str = '';
					if (lastPlanDate == null) {
						this.getDaysStr = '当前为电梯首次保养';
					} else {
						this.getDaysStr = `离上次保养完成${getDays(
							lastPlanDate,
							planDate.slice(0, 10)
						)}天`;
					}
					this.mPlanDate = res.data.planDate.slice(0, 10);
					resolve();
				});
			});
		},
		// 保养任务追踪
		initGetStep(planId) {
			getSelectWorkTracks({
				planId,
			}).then(async (res) => {
				if (res.code === 200) { 
					await this.getLastMaintenance(planId);
					let workArr = res.data.workLogs || [];
					let taskStatus = res.data.taskStatus || [];
					if (workArr.length > 0) {
						workArr = workArr.map((item) => {
							return {
								...item,
								extPlus: JSON.parse(item.ext || '{}'),
								aiResult: '',
								modelId: ''
							};
						});
						let takeTime =
              res.data.workDuration != 'null' ? Number(res.data.workDuration) : 0;
						this.planTimes = takeTime;
						if (takeTime > 60) {
							this.strText = '时间过长';
						}
						if (takeTime < 25) {
							this.strText = '时间过短';
						}
						this.dataArray = JSON.parse(JSON.stringify(workArr));
						this.dataArray.reverse();
						this.dataArray[this.dataArray.length - 1].getDaysStr = this.getDaysStr;
						this.dataArray[this.dataArray.length - 1].planDate = this.mPlanDate; 
						let obj = {
							createTime: '',
							executor: '签字完成',
							typeName: ' ',
							active: true,
						};
						let a = workArr.length - 1;
						let resultState = this.dataArray.some(
							(item) => item.planStatus === 4
						);
						let planStatusArr = [
							{
								createTime: '',
								executor: '待开始',
								typeName: '',
								active: true,
								status: 1,
							},
							{
								createTime: '',
								executor: '提交',
								typeName: '',
								active: true,
								status: 2,
							},
							{
								createTime: '',
								executor: '签字完成',
								typeName: '',
								active: true,
								status: 3,
							},
							{
								createTime: '',
								executor: '任务完成',
								typeName: ' ',
								active: false,
								status: 4,
							},
						];
						for (let i = 0; i < planStatusArr.length; i++) {
							if (planStatusArr[i].status === workArr[a].planStatus) {
								obj.executor = planStatusArr[i].executor;
								obj.typeName = planStatusArr[i].typeName;
								obj.active = planStatusArr[i].active;
							}
						}
						if (resultState) {
							obj.planStatus = 4;
							this.dataArray.shift();
							this.dataArray.unshift(obj);
						} else {
							this.dataArray.unshift(obj);
						} 
						this.getAiResults();
						this.$forceUpdate();
					}
				}
			});
		},
		// 异步获取ai结果
		async getAiResults() {
			for (let i = 0; i < this.dataArray.length; i++) {
				if (this.dataArray[i].extPlus && this.dataArray[i].extPlus.image) {
					const imgHead = await this.getHeadInfo(this.dataArray[i].extPlus.image);
					
					if (imgHead && imgHead['x-oss-meta-model-id']) {
						this.dataArray[i].modelId = imgHead['x-oss-meta-model-id'];
						this.dataArray[i].aiResult = imgHead['x-oss-meta-result'];
					}
				}
			}
			console.log('getAiResults', this.dataArray);
			this.$forceUpdate();
		},

		getHeadInfo(url) {
			if (url.indexOf('aliyuncs.com') == -1) {
				return getPathInfo(url);
			}
			return new Promise((resolve) => {
				// #ifdef H5
				this.http.head(url).then(header => {
					const newHeader = {};
					Object.keys(header).forEach(key => {
						// 转码，兼容中文字符 
						newHeader[key] = decodeURIComponent(header[key]);
					});
					resolve(newHeader);
				});
				// #endif

				// #ifndef H5
				uni.request({
					method: 'HEAD',
					url,
					success(res) {
						let header = res.header || {};
						Object.keys(header).forEach(key => {
							// 转码，兼容中文字符
							header[key] = decodeURIComponent(header[key]);
						});
						resolve(header);
					}, fail() {
						resolve({});
					}
				});
				// #endif
			});
		},
		// 配件任务追踪
		initPartsStep(planId) {
			getSelectWorkTracks({
				planId,
			}).then((res) => {
				if (res.code === 200) {
					let workTrackList = res.data.workLogs || [];
					let taskStatus = res.data.taskStatus || [];
					let dataArrayParts = this.dataArrayParts || [];
					if (workTrackList.length > 0) {
						let lastPlanStatus = workTrackList[workTrackList.length - 1].planStatus === 8 ? 7 : workTrackList[workTrackList.length - 1].planStatus;
						let lastPlanStatusIndex = this.dataArrayParts.findIndex(item => item.status == lastPlanStatus);
						for (let i = 0; i < dataArrayParts.length; i++) {
							for (let j = 0; j < workTrackList.length; j++) {
								if (dataArrayParts[i].status === workTrackList[j].planStatus) {
									workTrackList[j].extPlus = JSON.parse(workTrackList[j].ext || '{}');
									// if (workTrackList[j].planStatus < 6) {
									//   workTrackList[j].typeName = dataArrayParts[i].name;
									// }
									// if ([2,3,4,10,11,12].includes(workTrackList[j].planStatus) ) {
									//   workTrackList[j].passName = '审批通过';
									// }
									let planStatusIndex = this.dataArrayParts.findIndex(item => item.status == workTrackList[j].planStatus);
									if (lastPlanStatusIndex > planStatusIndex && ![8, 9].includes(workTrackList[j].planStatus)) {
										workTrackList[j].passName = '审核通过';
									}
									// if (!workTrackList[j].ext && workTrackList[j].planStatus != 8 && workTrackList[j].planStatus != 9) {
									//   workTrackList[j].passName = "审批通过";
									// }
									if (workTrackList[j].typeName === '提交配件申请' && j == 0) {
										workTrackList[j].passName = '发起';
									}
									if (workTrackList[j].typeName === '待处理' || workTrackList[j].typeName === '重新提交配件申请' || workTrackList[j].planStatus === 6) {
										workTrackList[j].passName = '';
									}
									if (workTrackList[j].extPlus && workTrackList[j].extPlus.type == 1 && (workTrackList[j].planStatus === 5 || workTrackList[j].planStatus === 6)) {
										workTrackList[j].transferName = '分配任务';
									}
									if (Object.keys(workTrackList[j].extPlus).length <= 0 && workTrackList[j].planStatus === 5) {
										workTrackList[j].transferName = '分配任务';
										let name = workTrackList[j].userNames == null ? '' : `【${workTrackList[j].userNames}`;
										workTrackList[j].transferNameTo = `${workTrackList[j].typeName}${name}`;
									}
									if (workTrackList[j].ext && workTrackList[j].extPlus.approveDesc === '审核不通过') {
										workTrackList[j].extPlus.comment = `终止原因：${workTrackList[j].extPlus.remark || '无'}`;
										workTrackList[j].errorName = '审核不通过';
										workTrackList[j].passName = '';
									}
									if (workTrackList[j].ext && workTrackList[j].extPlus.approveDesc === '审核退回') {
										workTrackList[j].extPlus.comment = `退回理由：${workTrackList[j].extPlus.remark || '无'}`;
										workTrackList[j].returnName = '审核退回';
										workTrackList[j].passName = '';
									}
								}
							}
						}
						this.dataArray = workTrackList.reverse();
						let obj = {
							createTime: '',
							executor: '已完成',
							extPlus: {},
							typeName: ' ',
							active: false,
						};
						let resultState = this.dataArray.some(
							(item) => item.planStatus === 7
						);
						console.log('配件任务追踪', resultState, this.dataArray);

						if (resultState) {
							obj.planStatus = 4;
							this.dataArray.shift();
							this.dataArray.unshift(obj);
						} else {
							this.dataArray.unshift(obj);
						}
					}
				}
			});
		},

		// 任务状态详情，维保员列表等信息
		getPlanDetail() {
			return new Promise((resolve) => {
				getPlandUser({ planId: this.elevatorDetail.planId }).then((res) => {
					// getPlanDetail({ planId:this.elevatorDetail.planId }).then(res => {
					this.userListArr = res.data || [];
					resolve();
				});
			});
		},
		handleBack() {
			uni.navigateBack({
				delta: 1,
			});
		},
		cutLenght(val) {
			if (val.length > 12) {
				return val.substring(0, 12) + '...';
			}
			return val;
		},
		// 查看图片
		seeClick(val) {
			this.$previewMedia({
				current: 0,
				sources: [val]
			});
			// this.$refs.previewwGuide.open()
		},
		seeClickDetial(item, type) {
			if (type === 1) {
				this.getPlanDetail();
				this.$refs.logPopup.open();
			}
			if (type === 2) {
				let needObj = {
					planId: this.elevatorDetail.planId,
					buildingAddress: this.elevatorDetail.buildingAddress,
					planCheckName: this.elevatorDetail.planCheckName,
					planDate: this.elevatorDetail.planDate,
					auditType: this.elevatorDetail.auditType,
					deferType: this.elevatorDetail.deferType,
				};
				uni.navigateTo({
					url:
            '/pageModules/yearTrial/operationLog?needObj=' +
            JSON.stringify(needObj),
				});
			}
		},
		showPath() {
			console.log('showPath', this.elevatorDetail);
			if (!this.elevatorDetail.latitude) {
				return;
			}
			uni.openLocation({
				latitude: parseFloat(this.elevatorDetail.latitude),
				longitude: parseFloat(this.elevatorDetail.longitude),
				name: this.elevatorDetail.buildingName,
				address: this.elevatorDetail.buildingAddress,
				scale: 18,
				complete: (e) => {
					console.log(e);
				},
				success(e) { },
			});
		},
		// 去电梯详情
		toInfos() {
			// console.log('区电梯也')
			let urls =
        '/subpages/elevator/projectInfo/elevatorInfoPage?id=' + this.elevatorDetail.id;
			if (this.repairState === 1) {
				urls =
          '/subpages/elevator/projectInfo/elevatorInfoPage?id=' +
          this.elevatorDetail.elevatorId;
			}
			uni.navigateTo({
				url: urls,
			});
		},
		// fetchElevtorDetail(){
		// 	return new Promise((reslove)=>{
		//      elevtorDetail
		// 	})
		// }
	},
};
</script>
<style>
page {
  background: #f3f6f8;
}
</style>
<style lang="scss" scoped>
@mixin fontColors($px, $count, $colour) {
  font-size: $px;
  font-weight: $count;
  color: $colour;
}

.taskStep {
  padding-bottom: 120rpx;

  .aa {
    position: fixed;
    z-index: 300;
    width: 100%;
    overflow: auto;
    background-color: #fff;
    box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(0, 0, 0, 0.12);
  }

  .header {
    background: #f3f6f8;
    height: 366rpx;
    // #ifdef H5 
    height: 200rpx;
    // #endif

    .bg {
      width: 376rpx;
      height: 366rpx;
      position: absolute;
      z-index: 9;
      top: 0;
      right: 0;
      // #ifdef H5 
      height: 200rpx;
      // #endif
    }

    .header_item {
      padding: 28rpx 40rpx;
      height: 400rpx;

      // #ifdef H5 
      height: 200rpx;
      // #endif
      // background: #f3f6f8;
    }

    .header_top {
      display: flex;
      // justify-content: space-between;
      align-items: center;
      margin-bottom: 4rpx;
      position: relative;
      z-index: 300;
      justify-content: space-between;

      .header_top_left {
        font-size: 38rpx;
        color: #333;
        font-weight: 600;
        display: flex;
      }

      .flex {
        text {
          width: 48rpx;
          display: inline-block;
          width: 16rpx;
          height: 16rpx;
          border-top: 2rpx #1b181b solid;
          border-right: 2rpx #1b181b solid;
          transform: rotate(45deg);
        }
      }

      .right {
        display: flex;
        color: #666;
        font-size: 24rpx;
        flex: 1;
        justify-content: flex-end;
      }
    }

    .header_bottom {
      position: relative;
      z-index: 10;
      font-size: 24rpx;
      color: #666;
    }

    .info {
      display: flex;
      justify-content: space-between;

      .header_bottom_left {
        display: flex;
        height: 40rpx;

        .str {
          width: 40rpx;
        }

        view {
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .content {
    // width: 100%;
    /* position: absolute; */
    /* margin: 0 20rpx; */
    background: #f3f6f8;
    padding: 0 20rpx;
    // padding-bottom: 120rpx;
    margin-bottom: 30rpx;

    .content_chi {
      width: 710rpx;
      margin: 0 auto;
      border-radius: 8rpx;
      background: #ffffff;

      margin-top: 30rpx;

      .t_name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333333;
        padding: 20rpx 20rpx 12rpx 30rpx;
      }

      .t_Times {
        margin-bottom: 30rpx;
        margin-left: 30rpx;
        font-size: 28rpx;
        color: #666666;
        display: flex;
        align-items: center;

        image {
          width: 28rpx;
          height: 28rpx;
          // vertical-align: middle;
        }

        text:nth-of-type(2) {
          background: #ffefe3;
          font-size: 24rpx;
          color: #fa6400;
          padding: 5rpx 10rpx 5rpx 10rpx;
          margin-left: 10rpx;
          border-radius: 4rpx;
        }
      }

      .stepInfoBox {
        margin-top: 12rpx;
      }
    }
  }

  .calendarEdit {
    background-color: #fff;
    min-height: 472rpx;
    border-radius: 8rpx 8rpx 0rpx 0rpx;
    position: relative;

    .edit_bor {
      width: 100%;
      padding: 20rpx 0;

      .down-btn {
        width: 64rpx;
        height: 10rpx;
        background: #d8d8d8;
        border-radius: 6rpx;
        margin: 0 auto;
      }
    }

    .edit_content {
      width: 680rpx;
      margin: 0 auto;

      .content_tit {
        @include fontColors(32rpx, 600, #333);
        margin-bottom: 20rpx;
      }

      .content_uper {
        display: flex;
        justify-content: space-between;
        border-bottom: 2rpx #eee solid;
        padding-bottom: 20rpx;
        font-size: 28rpx;
        color: #333333;
        margin-top: 32rpx;

        view:nth-of-type(1) {
          image {
            width: 32rpx;
            height: 32rpx;
            vertical-align: middle;
          }

          text {
            vertical-align: middle;
          }
        }

        view:nth-of-type(2) {
          font-weight: 600;
        }
      }

      .content_down {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;
        padding-bottom: 108rpx;

        view:nth-of-type(1) {

          // width: 300rpx;
          image {
            width: 32rpx;
            height: 32rpx;
            vertical-align: middle;
          }

          text {
            vertical-align: middle;
          }
        }

        view:nth-of-type(2) {
          // width: 300rpx;
        }
      }

      .content_lines {
        border-bottom: 2rpx #eee solid;
      }
    }
  }

  .BA_item_botm {
    position: fixed;
    bottom: 0;
    left: 0;
    // z-index: 9;
    height: 98rpx;
    display: flex;
    align-items: center;
    width: 100%;
    background: #fff;
    border-top: 2rpx #eee solid;

    .botm {
      width: 720rpx;
      margin: 0 auto;
      height: 70rpx;
      background: #0091ff;
      border-radius: 8rpx;
      line-height: 70rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 500;
      color: #ffffff;
    }

    .botms {
      background: #efefef;
    }
  }
}
</style>
